<!--
 * @author  dumeng
 新建/编辑调查问卷
-->
<template>
  <div class="survey-manage">
    <div class="page-title">新建/编辑调查问卷</div>
    <section v-loading="loading" class="page-main">
      <el-form ref="form" :model="form" :rules="rules" label-width="160px" class="form">
        <!-- <el-form-item label="创建方式" prop="createType">
          <el-radio-group v-model="form.createType">
            <el-radio v-for="(item, index) in dict.WJCJFS" :key="index" :label="item.dictValue" border @click.native="optionType(item.dictValue)">{{
              item.dictName
            }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="是否可以查看问卷" prop="isView">
          <el-radio-group v-model="form.isView">
            <el-radio label="0" border>否</el-radio>
            <el-radio label="1" border>是</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item v-if="form.createType === 'WJX'" label="问卷星url" prop="urlCreate">
          <el-input v-model="form.urlCreate" placeholder="请输入问卷星url地址" />
        </el-form-item> -->
        <el-form-item label="活动类型" prop="classifyId">
          <el-radio-group v-model="form.classifyId">
            <el-radio v-for="(item, index) in dict.HDZXFXPC" :key="index" :label="item.dictValue">{{ item.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="引导图" prop="coverImgId" required>
          <image-upload
            :key="uploadImg.imagecropperKey"
            v-model="form.coverImgId"
            :preview-id="uploadImg.viewId"
            :forever="true"
            :width="702"
            :view="uploadImg.view"
            :height="310"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
          />
        </el-form-item>
        <!-- <el-form-item label="简介">
          <el-input v-model="form.briefIntroduction" :rows="6" type="textarea" placeholder="请输入简介" />
        </el-form-item> -->
        <el-form-item label="开放范围" prop="openRange">
          <el-radio-group v-model="form.openRange">
            <el-radio v-for="v in dict.WJKFFW" :key="v.dictValue" :label="v.dictValue">{{ v.dictName }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.openRange === 'WJKFFW_BM'" label="部门" prop="orgId">
          <el-cascader ref="org" v-model="form.deptIds" style="width: 100%" collapse-tags clearable :props="orgProps" :options="orgTreeData" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始日期"
            style="width: 100%"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束日期"
            default-time="23:59:59"
            style="width: 100%"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item v-if="form.createType === 'LOAD'" label="问卷说明">
          <div>
            <tinymce v-if="showtinymce" v-model="form.remark" :height="300" />
          </div>
        </el-form-item>
        <el-form-item v-if="form.createType === 'LOAD'" label="问卷介绍">
          <div>
            <tinymce v-if="showtinymce" v-model="form.introduce" :height="300" />
          </div>
        </el-form-item>

        <!-- 加入抽奖相关 -->
        <el-form-item label="是否关联抽奖" prop="isDraw">
          <el-radio-group v-model="form.isDraw">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="职工端是否展示">
          <el-radio-group v-model="form.isAppVisit">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="可获得多少次抽奖机会" prop="drawChance">
          <el-input v-model.number="form.drawChance" placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="抽奖配置" prop="bigturntableId">
          <div>
            <el-button class="button-new-tag" size="small" @click="showInputRwys">抽奖配置</el-button>
          </div>
          <div>
            <el-tag v-if="dialogMultipleSelections.bigturntableName !== undefined" closable @close="handleCloses(dialogMultipleSelections)">
              {{ dialogMultipleSelections.bigturntableName || bigturntableName }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="抽奖弹窗标题" prop="popTitle">
          <el-input v-model="form.popTitle" autosize placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="抽奖弹窗引导按钮" prop="popButton">
          <el-input v-model="form.popButton" autosize placeholder="请输入" />
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="抽奖弹窗样式选择" prop="popStyle">
          <el-select v-model="form.popStyle" autosize placeholder="请选择">
            <el-option v-for="item in popStyleList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-image style="width: 375px;margin-top: 10px;" :src="popStyleList[form.popStyle].imagesOss" />
        </el-form-item>
        <el-form-item v-if="form.isDraw === '1'" label="抽奖活动说明" prop="drawExplain">
          <el-input v-model="form.drawExplain" autosize type="textarea" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入排序号（值越大，越靠前）" />
        </el-form-item>
      </el-form>
    </section>
    <section class="page-footer">
      <el-button
        style="padding: 10px 30px"
        @click="
          () => {
            $router.back()
          }
        "
      >取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
    <!-- 选择转盘 -->
    <el-dialog title="选择抽奖配置" :visible.sync="dialogFormVisibles" center fullscreen :close-on-click-modal="false">
      <choose-prize
        ref="resetAll"
        v-loading.fullscreen.lock="fullscreenLoadings"
        :before-list="beforeLists"
        :bigturntable-id="form.bigturntableId"
        @userData="userDatas"
      />
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px" @click="dialogFormVisibles = false">取消</el-button>
        <el-button style="padding: 8px 30px" type="primary" @click="insertUsers()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ChoosePrize from '@/views/activity/tphd/components/choosePrize'
import ImageUpload from '@/components/ImageUpload'
import { getDictByCode, getComAndOrgTree, insert, update, get } from '../api/index'
import { int } from '@/utils/validate'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { mapGetters } from 'vuex'
export default {
  name: 'SurveyManage',
  components: { ImageUpload, ChoosePrize },
  directives: { elDragDialog },
  data() {
    return {
      popStyleList: [
        {
          id: 0,
          name: '样式一',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/221202cc96931db26743919206900e8a2f390d.png'
        },
        {
          id: 1,
          name: '样式二',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/22120231f566d987e046718fe2eeae498020b6.png'
        },
        {
          id: 2,
          name: '样式三',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/2212027a85a262f6da40b8ab08ff5f8788f276.png'
        },
        {
          id: 3,
          name: '样式四',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/221202d7f2d0d9c2cd40d1a474301bdae7e155.png'
        },
        {
          id: 4,
          name: '样式五',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/2212026bf78ddb405c4affa83fab281ba8cf02.png'
        },
        {
          id: 5,
          name: '样式六',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/221202827b3f4b16a54addb0ae0fdc1d0ac910.png'
        },
        {
          id: 6,
          name: '样式七',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/221202ff3f9084d3bb4f1abb6ca173f24a253b.png'
        },
        {
          id: 7,
          name: '样式八',
          imagesOss: 'https://bjttsx-yanshi.oss-cn-beijing.aliyuncs.com/1/22/12/02/2212022fc3e4e4f9484ceabea370fab0c5e407.png'
        }
      ],
      dialogMultipleSelections: {},
      beforeLists: [],
      fullscreenLoadings: false,
      dialogFormVisibles: false,
      loading: false,
      form: {
        popTitle: '',
        popButton: '',
        popStyle: 0,
        bigturntableId: '',
        drawChance: 0,
        drawExplain: '',
        isDraw: '0',
        id: '',
        isView: '0',
        introduce: '',
        createType: 'LOAD',
        urlCreate: '',
        classifyId: '', // type
        name: '',
        coverImgId: '',
        // briefIntroduction: '',
        remark: '',
        startTime: '',
        endTime: '',
        openRange: '',
        isVotingPercentage: '1',
        deptIds: [],
        isVotersNumber: '1',
        showType: '',
        sort: '',
        isAppVisit: '1'
      },
      rules: {
        /* classifyId: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],*/
        // createType: [{ required: true, message: '请选择问卷创建的方式', trigger: 'blur' }],
        // urlCreate: [{ required: true, message: '请输入问卷星url地址', trigger: 'blur' }],
        introduce: [{ required: true, message: '请输入问卷介绍', trigger: 'blur' }],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 1,
            max: 200,
            message: '长度在 1 到 200 个字符',
            trigger: 'blur'
          }
        ],
        coverImgId: [{ required: true, message: '请上传引导图', trigger: 'change' }],
        startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
        endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
        openRange: [{ required: true, message: '请选择开放范围', trigger: 'change' }],
        deptIds: [{ required: true, message: '请选择部门', trigger: 'change' }],
        isVotingPercentage: [
          {
            required: true,
            message: '请选择是否展示已投票比例',
            trigger: 'change'
          }
        ],
        isVotersNumber: [
          {
            required: true,
            message: '请选择是否展示已投票人数',
            trigger: 'change'
          }
        ],
        sort: [{ required: false, validator: int, trigger: 'blur' }],
        bigturntableId: [
          {
            required: true,
            message: '请关联抽奖配置',
            trigger: 'blur'
          }
        ]
      },
      orgProps: {
        label: 'name',
        value: 'id',
        children: 'list',
        multiple: true,
        emitPath: false,
        checkStrictly: true
      },
      orgTreeData: [],
      state: 'create',
      dict: {
        WJKFFW: [], // 课程类型
        WJCJFS: [],
        HDZXFXPC: [] // type
      },
      uploadImg: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0
      },
      showtinymce: false
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    for (const key in this.dict) {
      this.getDict(key)
    }
    this.getOrgTree()
    if (this.$route.query.type === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.$router.back()
          }
        })
      }
    } else {
      this.showtinymce = true
    }
  },
  methods: {
    handleCloses(dialogMultipleSelections) {
      this.dialogMultipleSelections = {}
      this.form.bigturntableId = ''
    },
    // 确定选择抽奖配置
    insertUsers() {
      if (JSON.stringify(this.dialogMultipleSelections) === '{}') {
        this.$message({
          message: '请选择抽奖配置',
          type: 'warning'
        })
      } else {
        this.$set(this.form, 'bigturntableId', this.dialogMultipleSelections.id)
        this.dialogListLoadings = true
        this.dialogFormVisibles = false
      }
    },
    // 选择人物元素
    userDatas(val) {
      this.dialogMultipleSelections = val
    },
    // 选择转盘
    showInputRwys() {
      this.dialogFormVisibles = true
    },
    // optionType(dictValue) {
    //   console.log("111111",dictValue);
    //   if(dictValue === 'WJX'){
    //     var url = "https://www.wjx.cn/newwjx/mysojump/createblankNew.aspx";
    //     window.open(url, "_blank");
    //   }
    // },
    getOrgTree() {
      return new Promise((resolve, reject) => {
        getComAndOrgTree({ parentId: -1, orgId: this.user.orgId })
          .then((res) => {
            this.orgTreeData = res.data.data
          })
          .catch(() => {
            resolve([])
          })
      })
    },
    onSubmint() {
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params['deptIds'] = this.form.deptIds && this.form.deptIds.length > 0 ? this.form.deptIds.join(',') : ''
            return new Promise((resolve, reject) => {
              insert(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.back()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form)
            params['deptIds'] = this.form.deptIds && this.form.deptIds.length > 0 ? this.form.deptIds.join(',') : ''
            return new Promise((resolve, reject) => {
              update(params)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.$router.back()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 获取字典
     */
    getDict(code) {
      console.log('code', code)
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((res) => {
            this.dict[code] = res.data.data && res.data.data.length > 0 ? res.data.data[0].list : []
            if (this.state === 'update') {
              this.getData(this.$route.query.i)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id })
          .then((res) => {
            loading.close()
            const data = res.data.data
            for (const key in this.form) {
              if (key === 'deptIds' && data.deptIds) {
                this.form[key] = data.deptIds.split(',').filter((item) => {
                  return item
                })
              } else {
                this.form[key] = data[key]
              }
            }
            this.$set(this.form, 'popStyle', this.form.popStyle ? this.form.popStyle : 0)
            this.uploadImg.viewId = data.coverImgId
            this.$set(this, 'dialogMultipleSelections', {
              bigturntableName: res.data.data.bigturntableName,
              id: res.data.data.bigturntableId
            })
            this.showtinymce = true
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.survey-manage {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;
  .page-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;
    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .page-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;
    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }
    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }
    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }
    &:hover {
      overflow: auto;
    }
    .form {
      width: 1000px !important;
      margin: 0 auto;
      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }
  }
  .page-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }
}
</style>
